import ArticleItem from '@/components/ArticleItem';
import { useAppDispatch, useAppSelector } from '@/store';
import { getArticlesByIdAction, updateArticleByIdAction } from '@/store/action/article';
import { InfiniteScroll, PullToRefresh } from 'antd-mobile';
import { useEffect } from 'react';
import styles from './index.module.scss';
type Props = {
  channel_id: number;
  style: React.CSSProperties;
};

export default function ArticleList({ channel_id, style }: Props) {
  const dispatch = useAppDispatch();
  const { articleData } = useAppSelector((state) => state.article);
  const { currentId } = useAppSelector((state) => state.channel);
  const { results, pre_timestamp } = articleData[channel_id] || {};

  useEffect(() => {
    if (channel_id !== currentId) return;
    if (results) return;

    dispatch(getArticlesByIdAction(channel_id, Date.now()));
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [dispatch, channel_id, currentId]);

  const loadMore = async () => {
    await dispatch(updateArticleByIdAction(channel_id, Number(pre_timestamp)));
  };

  return (
    <PullToRefresh
      onRefresh={() => dispatch(getArticlesByIdAction(channel_id, Date.now()))}
    >
      <div className={styles.root} style={{ ...style }}>
        <div className="channel-list">
          {results?.map((item) => (
            <ArticleItem key={item.art_id} data={item} />
          ))}
          {results?.length && (
            <InfiniteScroll loadMore={loadMore} hasMore={!!pre_timestamp} />
          )}
        </div>
      </div>
    </PullToRefresh>
  );
}
